using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net;
using NetFtp.Core.Ftp;

public partial class Ftp : System.Web.UI.Page
{
    private FtpSession ftpSession;

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["USER_LOGIN"] == null)
                Response.Redirect("Default.aspx");

            ftpSession = new FtpSession(Session["HOST_FTP"].ToString(), int.Parse(Session["PORT_FTP"].ToString()), Session["LOGIN_FTP"].ToString(), Session["MDP_FTP"].ToString(), bool.Parse(Session["PASSIVE_FTP"].ToString()));

            if (Session["FOLDER_SESSION"] == null)
            {
                FtpSessionFolder path;
                path = new FtpSessionFolder(Server.MapPath(ConfigurationSettings.AppSettings["TmpFolder"]), "");
                Session["FOLDER_SESSION"] = path.Folder;
                Session["ID_SESSION"] = path.Id;
            }

            if (Page.IsPostBack == false)
            {
                string basename = Session["FOLDER_FTP"].ToString();

                List<FtpFile> listeall = (List<FtpFile>)ftpSession.ListDirectory(basename);
                gvFichier.DataSource = listeall;
                gvFichier.DataBind();
                for (int i = 0; i < gvFichier.Rows.Count; i++)
                {
                    if (((Label)(gvFichier.Rows[i].FindControl("Directory"))).Text == "True")
                    {
                        ((Image)(gvFichier.Rows[i].FindControl("imgFolder"))).Visible = true;
                        ((Image)(gvFichier.Rows[i].FindControl("imgFile"))).Visible = false;
                        ((Label)(gvFichier.Rows[i].FindControl("Taille"))).Visible = false;
                    }
                    else
                    {
                        ((Image)(gvFichier.Rows[i].FindControl("imgFolder"))).Visible = false;
                        ((Image)(gvFichier.Rows[i].FindControl("imgFile"))).Visible = true;
                        ((Label)(gvFichier.Rows[i].FindControl("Taille"))).Visible = true;
                    }
                }

                List<FtpFile> listedir = (List<FtpFile>)ftpSession.ListDirectoryDirOnly(basename);
                TreeNode root = new TreeNode();
                root.Selected = true;
                root.Value = "";
                root.Text = basename;
                foreach (FtpFile file in listedir)
                {
                    TreeNode node = new TreeNode(file.Name);
                    root.ChildNodes.Add(node);
                }
                tvArbo.Nodes.Add(root);
            }
        }
        catch (Exception ex)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "js1", "<script>alert(\"Error : " + ex.Message.Replace("\"", "'").Replace("\r\n", " ") + "\");</script>");
        }
    }

    private IList<FtpFile> copierrec(string directory, string racine)
    {
        List<FtpFile> retour = new List<FtpFile>();
        List<FtpFile> liste = (List<FtpFile>)ftpSession.ListDirectory(directory);

        foreach (FtpFile file in liste)
        {
            if (file.Directory)
            {
                file.Name = directory.Substring(racine.Length + 1) + "/" + file.Name;
                retour.Add(file);
                retour.AddRange(copierrec(file.FullName, directory));
            }
            else
            {
                file.Name = directory.Substring(racine.Length + 1) + "/" + file.Name;
                retour.Add(file);
            }
        }

        return retour;
    }

    protected void copier_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            List<FtpFile> files = new List<FtpFile>();

            for (int i = 0; i < gvFichier.Rows.Count; i++)
            {
                if (((CheckBox)(gvFichier.Rows[i].FindControl("Selected"))).Checked == true)
                {
                    FtpFile file = new FtpFile(tvArbo.SelectedNode.ValuePath + "/" + ((Label)gvFichier.Rows[i].FindControl("Fichier")).Text);

                    if (((Label)(gvFichier.Rows[i].FindControl("Directory"))).Text == "True")
                    {
                        file.Directory = true;
                        files.Add(file);
                        files.AddRange(copierrec(file.FullName, tvArbo.SelectedNode.ValuePath));
                    }
                    else
                    {
                        file.Directory = false;
                        files.Add(file);
                    }
                }
            }

            Session["MOVE_FILE"] = files;
        }
        catch (Exception ex)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "js1", "<script>alert(\"Error : " + ex.Message.Replace("\"", "'").Replace("\r\n", " ") + "\");</script>");
        }
    }

    protected void move_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            if (Session["MOVE_FILE"] == null)
                return;

            List<FtpFile> files = new List<FtpFile>();

            files = (List<FtpFile>)Session["MOVE_FILE"];

            foreach (FtpFile filedistant in files)
            {
                if (filedistant.Directory)
                {
                    ftpSession.MakeDirectory(tvArbo.SelectedNode.ValuePath + "/" + filedistant.Name);
                }
                else
                {
                    FileInfo filetmp = new FileInfo(filedistant.Name);
                    FileInfo filelocal = new FileInfo(Path.Combine(Session["FOLDER_SESSION"].ToString(), filetmp.Name));

                    ftpSession.Download(filedistant.FullName, filelocal.FullName);
                    ftpSession.Upload(filelocal.FullName, tvArbo.SelectedNode.ValuePath + "/" + filedistant.Name);
                }
            }

            Session["MOVE_FILE"] = null;

            Refresh();
        }
        catch (Exception ex)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "js1", "<script>alert(\"Error : " + ex.Message.Replace("\"", "'").Replace("\r\n", " ") + "\");</script>");
        }
    }

    protected void edit_Click(object sender, ImageClickEventArgs e)
    {
        for (int i = 0; i < gvFichier.Rows.Count; i++)
        {
            if (((CheckBox)(gvFichier.Rows[i].FindControl("Selected"))).Checked == true)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>window.open('EditFile.aspx?file=" + tvArbo.SelectedNode.ValuePath + "/" + ((Label)gvFichier.Rows[i].FindControl("Fichier")).Text + "', 'edit', 'width=700,height=600,toolbar=no,status=no,directories=no,menubar=no,location=no,scrollbars=yes,resizable=no')</script>");
                return;
            }    
        }
    }

    protected void upload_Click(object sender, ImageClickEventArgs e)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>window.open('UploadFile.aspx?folder=" + tvArbo.SelectedNode.ValuePath + "', 'upload', 'width=600,height=350,toolbar=no,status=no,directories=no,menubar=no,location=no,scrollbars=yes,resizable=no')</script>");
    }

    protected void addfile_Click(object sender, ImageClickEventArgs e)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>window.open('InputBox.aspx?mode=AddFile&value=" + tvArbo.SelectedNode.ValuePath + "', 'inputbox', 'width=600,height=250,toolbar=no,status=no,directories=no,menubar=no,location=no,scrollbars=yes,resizable=no')</script>");
    }

    protected void addfolder_Click(object sender, ImageClickEventArgs e)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>window.open('InputBox.aspx?mode=AddFolder&value=" + tvArbo.SelectedNode.ValuePath + "', 'inputbox', 'width=600,height=250,toolbar=no,status=no,directories=no,menubar=no,location=no,scrollbars=yes,resizable=no')</script>");
    }

    protected void download_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            if (Session["LAST_DOWNLOAD"] != null)
            {
                FileInfo lastfile = new FileInfo(Session["LAST_DOWNLOAD"].ToString());
                lastfile.Delete();
            }

            for (int i = 0; i < gvFichier.Rows.Count; i++)
            {
                if (((CheckBox)gvFichier.Rows[i].FindControl("Selected")).Checked == true)
                {
                    FileInfo filedistant = new FileInfo(Path.Combine(tvArbo.SelectedNode.ValuePath, ((Label)gvFichier.Rows[i].FindControl("Fichier")).Text));
                    FileInfo filelocal = new FileInfo(Path.Combine(Session["FOLDER_SESSION"].ToString(), filedistant.Name));

                    ftpSession.Download(Path.Combine(tvArbo.SelectedNode.ValuePath, ((Label)gvFichier.Rows[i].FindControl("Fichier")).Text), filelocal.FullName);
                    Session["LAST_DOWNLOAD"] = filelocal.FullName;
                    ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>window.open('DownloadFile.aspx?file=" + filelocal.FullName.Replace(@"\", @"\\") + "', 'download', 'width=500,height=150,toolbar=no,status=no,directories=no,menubar=no,location=no,scrollbars=yes,resizable=no')</script>");

                    return;
                }
            }
        }
        catch (Exception ex)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>alert(\"Error : " + ex.Message.Replace("\"", "'").Replace("\r\n", " ") + "\");</script>");
        }
    }

    private void deleterec(string directory)
    {
        List<FtpFile> liste = (List<FtpFile>)ftpSession.ListDirectory(directory);

        foreach (FtpFile file in liste)
        {
            if (file.Directory)
            {
                deleterec(file.FullName);
                ftpSession.DeleteDirectory(file.FullName);
            }
            else
            {
                ftpSession.DeleteFile(file.FullName);
            }
        }
    }

    protected void delete_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            for (int i = 0; i < gvFichier.Rows.Count; i++)
            {
                if (((CheckBox)(gvFichier.Rows[i].FindControl("Selected"))).Checked == true)
                {
                    if (((Label)(gvFichier.Rows[i].FindControl("Directory"))).Text == "True")
                    {
                        deleterec(tvArbo.SelectedNode.ValuePath + "/" + ((Label)gvFichier.Rows[i].FindControl("Fichier")).Text);
                        ftpSession.DeleteDirectory(tvArbo.SelectedNode.ValuePath + "/" + ((Label)gvFichier.Rows[i].FindControl("Fichier")).Text);
                    }
                    else
                    {
                        ftpSession.DeleteFile(tvArbo.SelectedNode.ValuePath + "/" + ((Label)gvFichier.Rows[i].FindControl("Fichier")).Text);
                    }
                }
            }

            Refresh();
        }
        catch (Exception ex)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>alert(\"Error : " + ex.Message.Replace("\"", "'").Replace("\r\n", " ") + "\");</script>");
        }
    }

    protected void rename_Click(object sender, ImageClickEventArgs e)
    {
        for (int i = 0; i < gvFichier.Rows.Count; i++)
        {
            if (((CheckBox)(gvFichier.Rows[i].FindControl("Selected"))).Checked == true)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>window.open('InputBox.aspx?mode=RenameFile&value=" + tvArbo.SelectedNode.ValuePath + "/" + ((Label)gvFichier.Rows[i].FindControl("Fichier")).Text + "', 'inputbox', 'width=600,height=250,toolbar=no,status=no,directories=no,menubar=no,location=no,scrollbars=yes,resizable=no')</script>");
                return;
            }
        }
    }

    protected void permission_Click(object sender, ImageClickEventArgs e)
    {

    }

    protected void tvArbo_SelectedNodeChanged(object sender, EventArgs e)
    {
        Refresh();
    }
    protected void select_Click(object sender, ImageClickEventArgs e)
    {
        for (int i = 0; i < gvFichier.Rows.Count; i++)
        {
            ((CheckBox)(gvFichier.Rows[i].FindControl("Selected"))).Checked = true;
        }
    }
    protected void refresh_Click(object sender, ImageClickEventArgs e)
    {
        Refresh();
    }
    private void Refresh()
    {
        try
        {
            string basename = tvArbo.SelectedNode.ValuePath;

            IList<FtpFile> listeall = ftpSession.ListDirectory(basename);
            gvFichier.DataSource = listeall;
            gvFichier.DataBind();
            for (int i = 0; i < gvFichier.Rows.Count; i++)
            {
                if (((Label)(gvFichier.Rows[i].FindControl("Directory"))).Text == "True")
                {
                    ((Image)(gvFichier.Rows[i].FindControl("imgFolder"))).Visible = true;
                    ((Image)(gvFichier.Rows[i].FindControl("imgFile"))).Visible = false;
                    ((Label)(gvFichier.Rows[i].FindControl("Taille"))).Visible = false;
                }
                else
                {
                    ((Image)(gvFichier.Rows[i].FindControl("imgFolder"))).Visible = false;
                    ((Image)(gvFichier.Rows[i].FindControl("imgFile"))).Visible = true;
                    ((Label)(gvFichier.Rows[i].FindControl("Taille"))).Visible = true;
                }
            }

            tvArbo.SelectedNode.ChildNodes.Clear();
            IList<FtpFile> listedir = ftpSession.ListDirectoryDirOnly(basename);
            foreach (FtpFile file in listedir)
            {
                TreeNode node = new TreeNode();
                node.Text = file.Name;
                node.Expanded = true;
                tvArbo.SelectedNode.ChildNodes.Add(node);
            }
        }
        catch (Exception ex)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "js1", "<script>alert(\"Error : " + ex.Message.Replace("\"", "'").Replace("\r\n", " ") + "\");</script>");
        }
    }
    protected void mdp_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("ChangeMdp.aspx");
    }
    protected void compte_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("UserAccount.aspx");
    }
    protected void deconnection_Click(object sender, ImageClickEventArgs e)
    {
        Session.Clear();
        Session.Abandon();
        Response.Redirect("Default.aspx");
    }
}
